#pragma once
#include<iostream>
#include<string>
#include<unordered_map>
#include <fstream>

#include "MyPthread/Log.hpp"
#include "Common.hpp"
using namespace LogMoudule;

const std::string gpath = "./";
const std::string gdictname = "dict.txt";
const std::string gsep = ": ";



class Dictionary
{
private:
    bool SplitString(std::string& line,std::string* key
                    ,std::string*value,std::string sep)
    {
        int pos = line.find(sep);
        if(pos == std::string::npos)return false;

        *key = line.substr(0, pos);
        *value = line.substr(pos+sep.size());
        if(key->empty() || value->empty()) return false;
        return true;
    }
    bool LoadDictionary()
    {
        std::string file = _path+ _dictname;
        //文件流
        std::ifstream in(file.c_str());

        if(!in.is_open())
        {
            LOG(LogLevel::ERROR) << "open file " << file << " error";
            return false;
        }

        std::string line;

        while(std::getline(in,line))
        {
            // happy: 快乐的
            std::string key;
            std::string value;
            if (SplitString(line, &key, &value, gsep))
            { // line -> key, value
                _dictionary.insert(std::make_pair(key, value));
            }
        }

        in.close();
        return true;

    }
    void Print()
    {
        for(auto &item : _dictionary)
        {
            std::cout << item.first << ":" << item.second<< std::endl;
        }
    }
public:
    Dictionary(const std::string& path = gpath,const std::string& dictname = gdictname)
    :_path(path),_dictname(dictname)
    {
        LoadDictionary();
        Print();
    }
    ~Dictionary()
    {

    }
    const std::string Translate(const std::string& word)
    {
        auto item = _dictionary.find(word);
        if(item == _dictionary.end())return "NULL";
        return item->second;
    }


private:
    std::string _path;
    std::string _dictname;
    std::unordered_map<std::string, std::string> _dictionary;
};
